<?php
/**
 * Created by PhpStorm.
 * User: zcq
 * Date: 2018/10/16
 * Time: 16:26
 */
namespace app\api\controller;

use think\Controller;
use think\Db;
use wxpay\lib\JsApiPay;
use wxpay\lib\WxPayApi;
use wxpay\lib\WxPayUnifiedOrder;

class Base extends Controller
{
    public $token;
    public $user;
    public $userId;
    public $ip;
    public $params;
    public $limit;
    public $wechat;
    public function __construct()
    {
        parent::__construct();
        header('Access-Control-Allow-Origin:*');
        //设置允许COOKIE
        header('Access-Control-Allow-Credentials:true');
        header('Access-Control-Allow-Headers:Token,Origin, X-Requested-With, Content-Type, Accept');
        header('Access-Control-Allow-Methods:POST,GET,PUT,DELETE,OPTIONS');
        $method = request()->method();
        if($method == 'OPTIONS'){
            echo 1;
            exit;
        }
        $this->wechat = config('wechat');
        $this->token = input('token');
        $this->params = input();
    }

    public function isLogin()
    {
        if(!$this->token)
            return false;

        if(env('API_TOKEN_DEMO',false)){
            $this->user = Db::name('member')->find(5);
            $this->userId = $this->user['id'];
            return true;
        }else{
            $this->user = cache($this->token);
            if($this->user){
                $this->userId= $this->user['id'];
                return true;
            }
        }

        return false;
    }

    public function renewUser()
    {
        $user = Db::name('member')->find($this->userId);
        if($user){
            cache($this->token,$user);
        }
    }

    public function getIp()
    {
        $ip = request()->ip();
        return $ip;
    }

    public function getPage()
    {
        return input('page/d')?:1;
    }

    public function getLimit()
    {
        if(empty($this->params['limit']) || (int) $this->params['limit'] <=0)
            return $this->limit?:20;
        return (int)$this->params['limit'];
    }

    public function apiReturn(int $code,$msg = null,$data=[])
    {

        $result = [
            'code'=>$code,
            'msg'=>$msg===null?$this->translate($code):$msg,
            'data'=>$data
        ];
        return json($result);
    }

    public function successReturn($data = [])
    {
        return $this->apiReturn(0,'success',$data);
    }

    public function errorReturn(int $code,$msg=null,$data=[])
    {
        return $this->apiReturn($code,$msg,$data);
    }

    public function translate($code)
    {
        return $error = config('error.'.$code)?:'系统繁忙，请稍后再试';
    }


}